package com.tanhua.sso.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.config.HuanXinConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: cloudy
 * @Description:
 * @Date: Created in 19:49 2021/1/10
 * @ModifiedBy:
 */
@Service
public class HuanXinTokenService {

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String REDIS_KEY = "HX_TOKEN";

    private static final ObjectMapper MAPPER = new ObjectMapper();

    public String getToken() {
        String token = this.redisTemplate.opsForValue().get(REDIS_KEY);
        if (StringUtils.isNotEmpty(token)){
            return token;
        }

        //拼接url
        String targetUrl = this.huanXinConfig.getUrl()
                + this.huanXinConfig.getOrgName()
                + "/" + this.huanXinConfig.getAppName()
                + "/token";
        //封装参数,post请求环信接口,获取token
        Map<String, Object> param = new HashMap<>();
        param.put("grant_type", "client_credentials");
        param.put("client_id", this.huanXinConfig.getClientId());
        param.put("client_secret", this.huanXinConfig.getClientSecret());

        //通过restTemplate来访问环信接口
        ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(targetUrl, param, String.class);
        if (responseEntity.getStatusCodeValue() != 200) {
            return null;
        }

        //请求成功,从返回结果中抽取出token信息
        String body = responseEntity.getBody();
        try {
            JsonNode jsonNode = MAPPER.readTree(body);
            String accessToken = jsonNode.get("access_token").asText();
            Long expiresIn = jsonNode.get("expires_in").asLong() - 86400;
            //获取到之后要将它放到redis中进行缓存,提前一天失效
            this.redisTemplate.opsForValue().set(REDIS_KEY,accessToken,expiresIn, TimeUnit.SECONDS);

            return accessToken;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
